package lib

import (
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"lib/mall/v1/models/userModels"
	"lib/mall/v1/plugins"
	"net/http"
)

type IContext interface {
	Success(data interface{}, message ...string)
	Fail(data interface{}, message ...string)
	ThrowError(error interface{})
	Response(result bool, data interface{}, message string)
	User(data interface{}) *userModels.User
	MustUser(data interface{})
	Validate(data interface{}) error
	MustValidate(data interface{})
}
type Context struct {
	*gin.Context
	Uid int
	Db  *gorm.DB
}

// Success 成功返回
func (c *Context) Success(data interface{}, message ...string) {
	msg := "ok"
	if len(message) > 0 {
		msg = message[0]
	}
	c.Response(true, data, msg)
}

// Fail 失败返回
func (c *Context) Fail(data interface{}, message ...string) {
	msg := "fail"
	if len(message) > 0 {
		msg = message[0]
	}
	c.Response(false, data, msg)
}

func (c *Context) Response(result bool, data interface{}, message string) {
	plugins.NewResponse().Json(c.Context, http.StatusOK, result, data, message, nil)
}

// User 获取登录用户信息
func (c *Context) User() *userModels.User {
	if c.Uid == 0 {
		return nil
	}
	var user *userModels.User
	res := c.Db.First(user, c.Uid)
	if res.RowsAffected != 0 {
		return user
	}
	return nil
}

// MustUser 获取登录用户信息，用户不存在或者为登录则报错
func (c *Context) MustUser(errorMessage ...string) *userModels.User {
	msg := "用户暂未登录"
	if len(errorMessage) > 0 {
		msg = errorMessage[0]
	}
	if c.Uid != 0 {
		c.ThrowError(msg)
	}
	var user *userModels.User
	res := c.Db.First(user, c.Uid)
	if res.RowsAffected == 0 {
		c.ThrowError(msg)
	}
	return user
}

// Validate 验证
func (c *Context) Validate(data interface{}) error {
	_ = c.ShouldBind(data)
	return plugins.NewValidator().Validate(data)
}

// MustValidate 验证并且抛出错误
func (c *Context) MustValidate(data interface{}) {
	err := c.Validate(data)
	if err != nil {
		c.ThrowError(err.Error())
	}
}

// ThrowError 抛出错误
func (c *Context) ThrowError(error interface{}) {
	panic(error)
}
